<template>
  <div>
    <el-card class="el-card">
      <!--条件搜索-->
      <el-form ref="roleQueryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            placeholder="请输入角色名称"
            clearable
            size="default"
            v-model="queryParams.roleName"
          />
        </el-form-item>
        <el-form-item label="权限字符串" prop="roleKey">
          <el-input
            placeholder="请输入权限字符串"
            clearable
            size="default"
            v-model="queryParams.roleKey"
          />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-select
            aria-placeholder="请选择角色状态"
            size="default"
            v-model="queryParams.status"
          >
            <el-option
              v-for="item in StatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="beginTime">
          <el-date-picker
            size="default"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="queryParams.beginTime"
            placeholder="请选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            size="default"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="queryParams.endTime"
            placeholder="请选择结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="querySearch">
            <template #icon>
              <i-ep-search />
            </template>
            查询
          </el-button>
          <el-button @click="resetQueryForm">
            <template #icon>
              <i-ep-refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <!--操作按钮-->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            v-if="hasPermission('api.sysRole.store')"
            plain
            type="primary"
            @click="handCreate"
          >
            <template #icon>
              <i-ep-plus />
            </template>
            新增
          </el-button>
        </el-col>
      </el-row>
      <!--列表-->
      <el-table
        border
        stripe
        class="w-full"
        header-cell-class-name="text-[#606266] !bg-[#eef1f6]"
        v-loading="tableData.loading"
        :data="tableData.data"
      >
        <template #empty>
          <el-empty :image-size="100" description="暂无数据" />
        </template>
        <el-table-column
          label="ID"
          header-align="center"
          v-if="false"
          prop="role_id"
        />
        <el-table-column
          header-align="center"
          label="角色名称"
          prop="role_name"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="权限字符串"
          prop="role_key"
        />
        <el-table-column
          header-align="center"
          label="角色状态"
          align="center"
          prop="status"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              size="large"
              :inline-prompt="true"
              :active-value="1"
              :inactive-value="2"
              active-color="#13ce66"
              inactive-color="#f5222d"
              active-text="启用"
              inactive-text="停用"
              :before-change="() => handStateChange(scope.row)"
              :disabled="!hasPermission('api.sysRole.state')"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="创建时间"
          prop="create_time"
        />
        <el-table-column
          header-align="center"
          label="描述"
          prop="description"
        />"
        <el-table-column
          header-align="center"
          align="center"
          fixed="right"
          label="操作"
          width="290"
        >
          <template #default="scope">
            <el-button
              v-if="hasPermission('api.sysRole.show')"
              type="primary"
              class="!ml-0"
              text
              @click="handUpdate(scope.row)"
            >
              <template #icon>
                <i-ep-edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-if="hasPermission('api.sysRole.destroy')"
              type="danger"
              class="!ml-0"
              text
              @click="handDestroy(scope.row)"
            >
              <template #icon><i-ep-delete /></template>
              删除
            </el-button>
            <el-button
              v-if="hasPermission('api.sysRole.assignPermissions')"
              type="success"
              class="!ml-0"
              text
              @click="handPermission(scope.row)"
            >
              <template #icon><i-ep-setting /></template>
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        class="justify-end"
        background
        @size-change="handleSizeChange()"
        @current-change="handleCurrentChange()"
        v-model:current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100, 500]"
        v-model:page-size="queryParams.pageSize"
        layout="total,sizes,prev,pager,next"
        :total="tableData.total"
        prev-text="上一页"
        next-text="下一页"
        :default-page-size="10"
        :pager-count="5"
      ></el-pagination>
    </el-card>
  </div>
  <RoleModel
    v-model:dialogVisible="dialogVisible"
    :role_id="role_id"
    @success="handSuccess"
  />
  <PermissionModel
    v-model:dialogVisible="permissionDialogVisible"
    :role_id="role_id"
    :title="title"
  />
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { StatusList } from './role.data'
import { RoleItem } from '@/api/auth/model/roleModel'
import { getList, state, destroy } from '@/api/auth/role'
import { FormInstance } from 'element-plus'
import { useForm } from '@/hooks'
import RoleModel from './roleModel.vue'
import PermissionModel from './permissionModel.vue'
import { usePermission } from '@/hooks/permission'

const roleQueryFormRef = ref<FormInstance>(null!)

const { resetForm } = useForm()
const { hasPermission } = usePermission()

const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const role_id = ref<number>(0)
const title = ref<string>('')

//搜索参数
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleName: '',
  roleKey: '',
  status: 0,
  beginTime: '',
  endTime: '',
})

//表格及分页数据
const tableData = reactive({
  loading: true,
  total: 0,
  data: [],
})

//获取列表数据
const getRoleList = async () => {
  try {
    const { code, data, message } = await getList(queryParams)
    if (code != 200) {
      ElMessage.error(message)
      return
    }
    tableData.total = data?.total || 0
    tableData.data = (data?.rows as never[]) || []
  } finally {
    tableData.loading = false
  }
}

//搜索
const querySearch = () => {
  getRoleList()
}
//搜索重置
const resetQueryForm = () => {
  resetForm(roleQueryFormRef.value)
  getRoleList()
}

//page-size 改变时触发
const handleSizeChange = () => {
  getRoleList()
}

//current-page 改变时触发
const handleCurrentChange = () => {
  getRoleList()
}

//修改状态
const handStateChange = (row: RoleItem) => {
  return new Promise<boolean>((resolve, reject) => {
    try {
      let text = row.status === 1 ? '禁用' : '启用'
      ElMessageBox.confirm(`确定要${text}${row.role_name}角色吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { code, message } = await state({
            roleId: row.role_id,
            status: row.status == 1 ? 2 : 1,
          })
          if (code != 200) {
            ElMessage.error(`${text}${message}`)
            reject(false)
          }
          ElMessage.success(`${text}${message}`)
          resolve(true)
        })
        .catch(() => {
          ElMessage.info('取消修改')
          reject(false)
        })
    } catch (error) {
      reject(false)
    }
  })
}

//添加
const handCreate = () => {
  dialogVisible.value = true
  role_id.value = 0
}

//更新
const handUpdate = (row: RoleItem) => {
  dialogVisible.value = true
  role_id.value = row.role_id
}

const handPermission = (row: RoleItem) => {
  permissionDialogVisible.value = true
  role_id.value = row.role_id
  title.value = row.role_name
}

//添加/修改成功后執行
const handSuccess = () => {
  getRoleList()
}

//刪除
const handDestroy = async (row: RoleItem) => {
  ElMessageBox.confirm(`确定要删除${row.role_name}角色吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, message } = await destroy({ role_id: row.role_id })
      if (code != 200) {
        ElMessage.error(`删除${row.role_name}${message}`)
        return
      }
      ElMessage.success(`删除${row.role_name}${message}`)
      getRoleList()
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

onMounted(() => {
  getRoleList()
})
</script>

<style scoped></style>
